const Koa = require('koa');
const consola = require('consola');
const session = require('koa-session');
const bodyParser = require('koa-bodyparser');
const cors = require('@koa/cors');
const routes = require('./routes');
const { Nuxt, Builder } = require('nuxt');
require("./websocket")

const app = new Koa();

// Import and Set Nuxt.js options
const config = require('../nuxt.config.js');
config.dev = (app.env === 'dev');
global.isDev = config.dev ;
console.info("isDev:"+global.isDev)
app.keys = ['fly']; // cookie
const sessionConfig = {
    key: 'fly-sess',
    // maxAge: 7 * 60 * 60 * 24 * 1000, // 7 day
    maxAge: 10 * 60 * 60 * 1000, // 4 hour
    overwrite: true,
    // httpOnly: true,
    signed: true,
    renew: false,
    rolling: false
};

if(!global.startTime) global.startTime = parseInt(new Date().getTime()/60000);

async function start() {
    // Instantiate nuxt.js
    const nuxt = new Nuxt(config);

    const {
        host = process.env.HOST || '0.0.0.0',
        port = process.env.PORT || 3000
    } = nuxt.options.server;


    app.use(session(sessionConfig, app));
    app.use(bodyParser());
    app.use(cors());
    app.use(routes.routes(), routes.allowedMethods());


    // Build in development
    if (config.dev) {
        const builder = new Builder(nuxt);
        await builder.build();
    } else {
        await nuxt.ready();
    }

    app.use(ctx => {
        ctx.status = 200;
        ctx.req.session = ctx.session;
        ctx.respond = false; // Bypass Koa's built-in response handling
        ctx.req.ctx = ctx; // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
        nuxt.render(ctx.req, ctx.res);
    });

    app.listen(port, host);
    

    if(global.mainWin){
        // global.mainWin.maximize();
        global.mainWin.loadURL("http://localhost:8888/")
        global.tipWin.loadURL('http://localhost:8888/tips/event')
        global.tradeWin.loadURL('http://localhost:8888/trade/main')
        global.popWin.loadURL('http://localhost:8888/trade/popWin')
        // global.popWin.maximize();
    }

    consola.ready({
        message: `Server listening on http://${host}:${port}`,
        badge: true
    });
}

start();
